<?php
	defined( '_JEXEC' ) or die( 'Restricted access' );
	jimport( 'joomla.application.component.model' );
	require_once(JPATH_COMPONENT.DS.'libraries'.DS.'core.php' );
	include_once(JPATH_COMPONENT.DS.'libraries'.DS.'core.php');
	require_once(JPATH_COMPONENT.DS.'data'.DS.'implFusionTables'.DS.'FTDAOFactory.php');
	
	class ModelSocialRoutesRouteList extends JModel
	{
		var $_routes = null;
		var $_userID = null;
		var $_total = null;
		var $_route = null;
		var $_myroute = null;
		//var $_pageNav = null;
		
		function __construct()
		{
			parent::__construct();
			
//			$mainframe = JFactory::getApplication();
//
//			// Get the pagination request variables
//			$limit = $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', 4, 'int' );
//			$limitstart = JRequest::getVar('limitstart', 0);
//			
//			// Set the limit variable for query later on
//			$this->setState('limit', $limit); 
//			$this->setState('limitstart', $limitstart);
		}
		
		private function getUserMyRoutes(){
			//Take routes from MyRoutes
			$daoUserRoutes=JDAOFactory::getInstance()->getDAORoute();
			$myAddedRoutes=$daoUserRoutes->getUserRoutes($this->_userID);

			return $myAddedRoutes;
		}
		
		
		function similar(){
			
	    	//Funcion que nos devuelve la ruta mas parecida cerca de donde estamos
	    	//******************hay que realizar el filtrado**********************
	    
	    
	        $this->_userID=JRequest::getVar('userid', CFactory::getUser()->get('id'));	
			$this->_routes=$this->getSimilarRoutes();
		
  
            return $this->_routes;
							
		}

		private function getSimilarRoutes(){
			
				
			$keywords = JRequest::getVar('keywords', 'Elorrio');
			$circleRadius = 1000; 
			$ok=1;
			$topAlturaMedia=50;
			$topAltura=50;
			$topDesnivelMedio=2;
			
		
			//Se calcula la distancia
			$maxDistance=$this->_route->getDistance()+10;
			$minDistance=$this->_route->getDistance()-10;
			
			//Se calcula cual es la altura Máxima
			$maxHigh=$this->alturaMaxima($this->_route);
			
			//Se calcula cual es la altura Media
			$averageHigh=$this->alturaMedia($this->_route);
			
			//desnivel Medio
			$averageDesnivel=$this->desnivelMedio($this->_route);
			
			//se ejecuta la función para buscar las rutas cercanas
			$daoFTRoutes=FTDAOFactory::getInstance()->getDAORoute();
			
			$location=$this->getLocation($keywords);
			
			$nearestRoutes=$daoFTRoutes->getNearestRoutesSimilar($location,$circleRadius,$maxDistance,$minDistance);
		
	        foreach($nearestRoutes as $route){
	        	
	        	// Se comprueba si las rutas seleccionas cumplen las condiciones de altura y % de elevación
				$ok=1;
			
				   	$ok = $this->comprobarRuta($route,$maxHigh,$averageHigh,$averageDesnivel,$topAlturaMedia,$topAltura,$topDesnivelMedio);
				  
				     if ($ok==1){
					
						$routes[] =$route;
						 
					 }
	
			    }
				
				if ($routes != null)
	            $routes=$this->deleteRepeatedRoutes($routes);
			
			
            $this->_total=count($routes);
            $this->_routes=$routes;
            
            return $this->_routes;
		} 	 	
		
		
		function comprobarRuta($route,$maxHigh,$averageHigh,$averageDesnivel,$topAlturaMedia,$topAltura,$topDesnivelMedio){
			$ok=1;

			$daoJRoute=JDAOFactory::getInstance()->getDAORoute();
			$this->_myroute=$daoJRoute->getRoute($route->getId());
			
			if($this->_myroute->getElevation()!='' && $this->_myroute->getElevation()!=null){
				
			if (($this->alturaMedia($this->_myroute) > $averageHigh+$topAlturaMedia) or ($this->alturaMedia($this->_myroute) < $averageHigh-$topAlturaMedia))
				$ok=0;
			if (($this->alturaMaxima($this->_myroute) > $maxHigh+$topAltura) or ($this->alturaMaxima($this->_myroute) < $maxHigh-$topAltura))
				$ok=0;
			if (($this->desnivelMedio($this->_myroute) > $averageDesnivel+$topDesnivelMedio) or ($this->desnivelMedio($this->_myroute) < $averageDesnivel-$topDesnivelMedio))
				$ok=0;
			}else{$ok=0;}
			
			return($ok);
		}
		
	    function readRoute($id){
			$daoJRoute=JDAOFactory::getInstance()->getDAORoute();
			$this->_route=$daoJRoute->getRoute($id);
			return $this->_route;
		}
		
		function alturaMaxima($ruta){
			$elevationArray=$ruta->getElevation();
			$elevationSplit = explode(",", $elevationArray);
			$max=$elevationSplit[0];
			foreach($elevationSplit as $elevationtoken){
				if ($elevationtoken>$max){
					$max=$elevationtoken;
				}
			}
	
			return($max);
		}
		
		function alturaMedia($ruta){
			$elevationArray=$ruta->getElevation();
			$elevationSplit = explode(",", $elevationArray);
			$max=0;
			foreach($elevationSplit as $elevationtoken){

					$max=$max+$elevationtoken;
				
			}
		
			return($max/sizeof($elevationSplit));
		}
		
		function desnivelMedio($ruta){
			
			
			$coordinatesArray=$ruta->getRawCoordinates();
			$ElevationArray=$ruta->getElevation();
			
			$coordinatesSplit = explode(",", $coordinatesArray);
			$coordinatesZero  = explode(" ", $coordinatesSplit[1]);
			$coordenadaVieja1 = $coordinatesZero[0];
			$coordenadaVieja2 = $coordinatesZero[1];
			$average=0;
			$i=0;
			$ElevacionAnterior=$ElevationArray[0];
			$total=0;
			
			//Calculo la distancia entre coordenadas
			foreach($coordinatesSplit as $coordenadatoken){

					$coordenadaPartida = explode(" ", $coordenadatoken);
					//echo"Cordenada vieja-->".$coordenadaVieja1."--".$coordenadaVieja2."          Cordenada nueva-->".$coordenadaPartida[1]."--".$coordenadaPartida[0]."                                                                               ";
					$distancia = $this->distance($coordenadaVieja1, $coordenadaVieja2, $coordenadaPartida[1], $coordenadaPartida[0]);
					//Diferencia de elevaación
					$difEle = $ElevationArray[i]- $ElevAnter;
					//Calculamos cual es el porcentaje de elevacion
					
					if ($distancia !=0){
					
					$porcentaje= ((100*$difEle)/$distancia);
					
					$total=$total+$porcentaje;
					}
				
					$coordenadaVieja1 = $coordenadaPartida[1];
			        $coordenadaVieja2 = $coordenadaPartida[0];
					$i++;
				   
			}
		
			return ($total/$i);
			
			
		}

	private function distance($lat1, $lng1, $lat2, $lng2, $miles = false)
{
	$pi80 = M_PI / 180;
	$lat1 *= $pi80;
	$lng1 *= $pi80;
	$lat2 *= $pi80;
	$lng2 *= $pi80;
 
	$r = 6372.797; // mean radius of Earth in km
	$dlat = $lat2 - $lat1;
	$dlng = $lng2 - $lng1;
	$a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
	$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
	$km = $r * $c;
 
	return ($miles ? ($km * 0.621371192) : ($km*1000));
}
		
		
		private function getUserCreatedRoutes(){
			//Take the routes which I am the creator of
			$daoJRoutes=JDAOFactory::getInstance()->getDAORoute();
			$myCreatedRoutes=$daoJRoutes->getUserCreatedRoutes($this->_userID);
	
            return $myCreatedRoutes;
		}
		
		private function deleteRepeatedRoutes($routes){
			for($i=0;$i<count($routes);$i++){
				if(isset($routes[$i])){
					for($j=$i+1;$j<count($routes);$j++){
						if(isset($routes[$j])&&($routes[$j]->getId()==$routes[$i]->getId())){
							unset($routes[$j]);
						}
					}
				}
			}
			return array_values($routes);
		}
		
		private function getLocation($keywords){
			$geocoder=new SRGeocoder();
	        $location=null;
	        $location=$geocoder->geocode($keywords);
	        return $location;
		}
		
		function searchRoutes(){
		
			//GET REQUEST PARAMETERS
			//$keywords = JRequest::getVar('keywords', null);
			$keywords = JRequest::getVar('keywords', '');
			$circleRadius = JRequest::getVar('circleRadius', 10); 
			if($circleRadius==0){
				$circleRadius=10;
			}
			$circleRadius=$circleRadius*1000; 
			$maxDistance = JRequest::getVar('maxDistance', ''); 
			
			$daoFTRoutes=FTDAOFactory::getInstance()->getDAORoute();
			
			if($keywords!='' && $keywords!=null){
				
				//GET ROUTES BY KEYWORDS IN TITLE
				$routes=$daoFTRoutes->getRoutesDescByKeywords($keywords,$maxDistance);
	            //GET ROUTES BY PROXIMITY TO AN AREA
	            if($keywords!=""){
	            	$location=$this->getLocation($keywords);
					$nearestRoutes=$daoFTRoutes->getNearestRoutes($location,$circleRadius,$maxDistance);
	            	foreach($nearestRoutes as $route){
						$routes[] =$route;
	            	}
		      	}
	            $routes=$this->deleteRepeatedRoutes($routes);
			}
			else{
				$routes=$daoFTRoutes->getRoutesByDistance($maxDistance);
			}
            $this->_total=count($routes);
            $this->_routes=$routes;
            
            return $this->_routes;
		}
		
//		function getPagination(){
//			jimport('joomla.html.pagination');
//			if(empty($this->_pageNav)){
//				$this->_pageNav = new JPagination($this->_total, $this->getState('limitstart'), $this->getState('limit'));
//			}
//			return $this->_pageNav;	
//		}
		
		function getUserRoutes(){ 
			$this->_userID=JRequest::getVar('userid', CFactory::getUser()->get('id'));
			
			$myAddedRoutes=$this->getUserMyRoutes();
			$myCreatedRoutes=$this->getUserCreatedRoutes();
			
            $this->_routes=array_merge($myAddedRoutes,$myCreatedRoutes);
            $this->_total=count($this->_routes);
            return $this->_routes;
		}
		
		function getUser(){
			return CFactory::getUser($this->_userID);
		}
		
		function getRoutes(){
			if ($this->_routes != null)
			return array_slice($this->_routes,$this->getState('limitstart'),$this->getState('limit'));
		}
	}
?>